package com.qyhl.webtv.module_live.teletext.chatroom;

import android.os.Build;
import android.os.Bundle;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.avos.avoscloud.im.v2.AVIMClient;
import com.avos.avoscloud.im.v2.AVIMConversation;
import com.avos.avoscloud.im.v2.AVIMConversationsQuery;
import com.avos.avoscloud.im.v2.AVIMException;
import com.avos.avoscloud.im.v2.AVIMMessage;
import com.avos.avoscloud.im.v2.AVIMMessageManager;
import com.avos.avoscloud.im.v2.AVIMMessageOption;
import com.avos.avoscloud.im.v2.callback.AVIMClientCallback;
import com.avos.avoscloud.im.v2.callback.AVIMConversationCallback;
import com.avos.avoscloud.im.v2.callback.AVIMConversationQueryCallback;
import com.avos.avoscloud.im.v2.callback.AVIMMessagesQueryCallback;
import com.avos.avoscloud.im.v2.messages.AVIMTextMessage;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.entity.live.TeleTextMessageBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.ViewPageFragment;
import com.qyhl.webtv.module_live.R;
import com.qyhl.webtv.module_live.R2;
import com.qyhl.webtv.module_live.common.TeleTextInterface;
import com.qyhl.webtv.module_live.utils.Event;
import com.qyhl.webtv.module_live.utils.ReportPopupWindow;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.umeng.analytics.MobclickAgent;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.leancloud.chatkit.LCChatKit;
import es.dmoral.toasty.Toasty;

/**
 * 图文聊天室
 * Created by jizhou on 2017/7/6.
 */

public class TeleTextCommentFragment extends ViewPageFragment implements TeleTextInterface.TeleTextComment {
    @BindView(R2.id.comment_refresh)
    SmartRefreshLayout commentRefresh;
    @BindView(R2.id.chat_room)
    RecyclerView chatRoom;
    @BindView(R2.id.layout)
    LoadingLayout layout;

    private String chatRoomId;
    private AVIMConversation conversation;
    private AVIMMessageOption messageOption;
    private TeleTextMessageHandler messageHandler;
    private AVIMMessage lastMessage;
    private List<AVIMMessage> historyMessage;
    private AVIMClient client;

    private String type, userId, sceneId;

    public void setType(String type) {
        this.type = type;
    }

    private LinkedList<TeleTextMessageBean> list;
    private MultiItemTypeAdapter<TeleTextMessageBean> mAdapter;
    private boolean online = false;

    public void setSceneId(String sceneId) {
        this.sceneId = sceneId;
    }

    public void setChatRoomId(String chatRoomId) {
        this.chatRoomId = chatRoomId;
    }

    public static TeleTextCommentFragment newInstance(String chatRoomId, String type, String sceneId) {
        TeleTextCommentFragment fragment = new TeleTextCommentFragment();
        fragment.setChatRoomId(chatRoomId);
        fragment.setSceneId(sceneId);
        fragment.setType(type);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.live_fragment_teletext_comment, container, false);
            ButterKnife.bind(this, rootView);
            init();//初始化
        }
        return rootView;
    }

    private void init() {
        layout.setErrorText("连接聊天室失败");
        layout.setReloadButtonText("点击重连");
        layout.setStatus(LoadingLayout.Loading);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if ("0".equals(type)) {
                chatRoom.setNestedScrollingEnabled(true);
            } else {
                chatRoom.setNestedScrollingEnabled(false);
            }
        }
        messageHandler = new TeleTextMessageHandler();

        //注册自定义的消息类型
        AVIMMessageManager.registerMessageHandler(AVIMTextMessage.class, messageHandler);
        BusFactory.getBus().register(this);

        list = new LinkedList<>();
        //初始化适配器
        mAdapter = new MultiItemTypeAdapter<>(getContext(), list);
        mAdapter.addItemViewDelegate(new TeleTextCommentMyAdapter(getContext()));
        mAdapter.addItemViewDelegate(new TeleTextCommentOtherAdapter(getContext()));
        chatRoom.setLayoutManager(new LinearLayoutManager(getContext()));
        chatRoom.setAdapter(mAdapter);

        //配置刷新
        commentRefresh.setDisableContentWhenRefresh(true);
        commentRefresh.setEnableOverScrollBounce(true);
        commentRefresh.setEnableHeaderTranslationContent(true);
        commentRefresh.setEnableLoadMore(false);
        commentRefresh.setRefreshHeader(new MaterialHeader(getContext()));

        commentRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                if (lastMessage != null && conversation != null) {
                    conversation.queryMessages(lastMessage.getMessageId(), lastMessage.getTimestamp(), 10, avimMessagesQueryCallback);
                }
                commentRefresh.finishRefresh();
            }
        });

        mAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                    @Override
                    public void login(boolean isLogin) {
                        if(isLogin){
                            ReportPopupWindow reportPopupWindow = new ReportPopupWindow(getActivity(), sceneId, list.get(i));
                            reportPopupWindow.showPopupWindow();
                        }else{
                            RouterManager.routerLogin(getActivity(), 0);
                        }
                    }

                    @Override
                    public void error(String s) {

                    }
                });

            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                return false;
            }
        });

        //内容显示
        layout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                if (online) {
                    if (conversation == null) {
                        findChatRoom();
                    } else {
                        connectChatRoom();
                    }
                } else {
                    connectService();
                }
            }
        });

        //初始化聊天室
        messageOption = new AVIMMessageOption();
        messageOption.setPriority(AVIMMessageOption.MessagePriority.Normal);
        String nickName = CommonUtils.getInstance().getNickName();
        if (StringUtils.isNotEmpty(nickName)) {
            userId = nickName;
//            tom = AVIMClient.getInstance(nickName);
        } else {
            userId = "游客";
//            tom = AVIMClient.getInstance("游客");
        }
        connectService();
    }

    //连接服务器
    private void connectService() {

        LCChatKit.getInstance().open(userId, new AVIMClientCallback() {
            @Override
            public void done(AVIMClient avimClient, AVIMException e) {
                if (e == null) {
                    client = avimClient;
                    online = true;
                    if (client != null) {
                        findChatRoom();
                    }
                } else {
                    layout.setStatus(LoadingLayout.Error);
                }
            }
        });
    }

    //查找聊天室
    private void findChatRoom() {
        AVIMConversationsQuery query = client.getConversationsQuery();
        query.whereEqualTo("objectId", chatRoomId);
        query.findInBackground(new AVIMConversationQueryCallback() {
            @Override
            public void done(List<AVIMConversation> list, AVIMException e) {
                if (e == null) {
                    if (list != null && !list.isEmpty()) {
                        conversation = list.get(0);
                        connectChatRoom();
                    } else {
                        layout.setStatus(LoadingLayout.Error);
                    }
                } else {
                    layout.setStatus(LoadingLayout.Error);
                }
            }
        });
    }

    //加入聊天室
    private void connectChatRoom() {
        conversation.join(new AVIMConversationCallback() {
            @Override
            public void done(AVIMException e) {
                if (e == null) {
                    conversation.queryMessages(10, avimMessagesQueryCallback);
                    layout.setStatus(LoadingLayout.Success);
                } else {
                    layout.setStatus(LoadingLayout.Error);
                }
            }
        });
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMessage(Event.TeleTextEventMessage event) {
        if (event != null && event.getMsg() != null) {
            AVIMTextMessage msg = (AVIMTextMessage) event.getMsg();
            if (msg != null && msg.getAttrs() != null) {
                list.add(translateMessage(event.getMsg()));
                mAdapter.notifyItemInserted(list.size() - 1);
                chatRoom.scrollToPosition(list.size() - 1);
            }
        }
    }

    private AVIMMessagesQueryCallback avimMessagesQueryCallback = new AVIMMessagesQueryCallback() {
        @Override
        public void done(List<AVIMMessage> list, final AVIMException e) {
            if (e == null) {
                if (list != null && !list.isEmpty()) {
                    lastMessage = list.get(0);
                    historyMessage = list;
                    Collections.reverse(historyMessage);
                    boolean scr = TeleTextCommentFragment.this.list.isEmpty();
                    for (AVIMMessage message : historyMessage) {
                        AVIMTextMessage msg = (AVIMTextMessage) message;
                        if (msg != null && msg.getAttrs() != null) {
                            TeleTextCommentFragment.this.list.add(0, translateMessage(message));
                        }
                    }
                    mAdapter.notifyDataSetChanged();
                    if (scr) {
                        chatRoom.scrollToPosition(TeleTextCommentFragment.this.list.size() - 1);
                    }
                } else {
                    Toasty.normal(getContext(), "没有更多了").show();
                }
            } else {
                Toasty.error(getContext(), e.getMessage() == null ? "null" : e.getMessage()).show();
            }
        }
    };

    @Override
    public void sendComment(final String comment) {
        final AVIMTextMessage msg = new AVIMTextMessage();
        msg.setText(comment);
        Map<String, Object> attributes = new HashMap<>();
        attributes.put("nickName", CommonUtils.getInstance().getNickName());
        attributes.put("headIcon", CommonUtils.getInstance().getUserLogo());
        attributes.put("id", CommonUtils.getInstance().getUserName());
        msg.setAttrs(attributes);
        if (conversation != null) {
            conversation.sendMessage(msg, messageOption, new AVIMConversationCallback() {
                @Override
                public void done(AVIMException e) {
                    if (e == null) {
                        //发送成功！
                        BusFactory.getBus().postSticky(new Event.TeleTextEventMessage(msg));
                    } else {
                        //发送失败
                        Toast.makeText(getActivity(), "发送失败，请稍后重试！", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        } else {
            layout.setStatus(LoadingLayout.Error);
            Toast.makeText(getActivity(), "连接聊天室失败！", Toast.LENGTH_SHORT).show();
        }

    }

    private TeleTextMessageBean translateMessage(AVIMMessage msg) {
        TeleTextMessageBean bean = new TeleTextMessageBean();
        AVIMTextMessage textMessage = (AVIMTextMessage) msg;
        if (textMessage == null || textMessage.getAttrs() == null || textMessage.getAttrs().get("headIcon") == null) {
            bean.setLogo("默认");
        } else {
            bean.setLogo(textMessage.getAttrs().get("headIcon").toString());
        }

        if (textMessage == null || textMessage.getAttrs() == null || textMessage.getAttrs().get("id") == null) {
            bean.setUsername("未知");
        } else {
            bean.setUsername(textMessage.getAttrs().get("id").toString());
        }

        if (textMessage == null || textMessage.getAttrs() == null || textMessage.getText() == null) {
            bean.setMessage("");
        } else {
            bean.setMessage(textMessage.getText());
        }

        if (textMessage == null || textMessage.getAttrs() == null || textMessage.getAttrs().get("nickName") == null) {
            bean.setNickname(StringUtils.encodePhoneNum(bean.getUsername()));
        } else {
            bean.setNickname(textMessage.getAttrs().get("nickName").toString());
        }
        return bean;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        BusFactory.getBus().unregister(this);
        //注销
        AVIMMessageManager.unregisterMessageHandler(AVIMTextMessage.class, messageHandler);
        LCChatKit.getInstance().close(new AVIMClientCallback() {
            @Override
            public void done(AVIMClient avimClient, AVIMException e) {
                Log.i("@@", "退出聊天室！");
            }
        });
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        //umeng
        MobclickAgent.onPageStart("图文直播聊天室");
        MobclickAgent.onResume(getContext());
    }


    @Override
    public void onPause() {
        super.onPause();
        //umeng
        MobclickAgent.onPageEnd("图文直播聊天室");
        MobclickAgent.onPause(getContext());
    }


}
